from .models import Xueyuan_zongbiao,xueyuan_jiaowu_genjinlog,Banji,Xueyuan_Zilao
from django import forms
from django.utils import timezone
from KeHu.models import KeHu

class xueyuan_form(forms.ModelForm):
    class Meta:
        model = Xueyuan_zongbiao
        fields = ('kehu', )

class tzzy_banji_xueyuan_UpdateForm(forms.ModelForm):
    """班级学员更新表单"""
    class Meta:
        model = Banji
        fields = ('xueyuan', )
        widgets = {'xueyuan': forms.CheckboxSelectMultiple()}

    def save(self, banji_instance, commit=True):
            instance = super().save(commit=False)
            selected_xueyuan = self.cleaned_data['xueyuan']
            instance.xueyuan.set(selected_xueyuan)  # 更新多对多关系
            if commit:
                # 通常情况下，我们不需要在这里调用banji_instance.save()，因为set方法会处理关系
                # 但如果Banji实例的其他字段也被更新，则可能需要调用
                pass
            for xueyuan in instance.xueyuan.all():
                print(f'学员入班时间：{xueyuan.xueyuan_jinbantime}')
                if xueyuan.xueyuan_jinbantime is None or xueyuan.xueyuan_jinbantime == '':
                    xueyuan.xueyuan_jinbantime = timezone.now()  # 设置为当前时间
                    xueyuan.save()
            if commit:
                instance.save()
            print(f"sdssdsdsdsd--------------------{instance}")
            return instance

class Banji_Xueyuan_Upadd_Form(forms.ModelForm):
    """班级学员更新表单"""
    class Meta:
        model = Banji
        fields = ('xueyuan', )
        widgets = {'xueyuan': forms.CheckboxSelectMultiple()}
    def save(self, commit=True):
            """保存表单"""
            instance = super().save(commit=False)
            for xueyuan in instance.xueyuan.all():# 遍历班级中的所有学员
                print(f'学员入班时间：{xueyuan.xueyuan_jinbantime}')
                if xueyuan.xueyuan_jinbantime is None or xueyuan.xueyuan_jinbantime == '':
                    xueyuan.xueyuan_jinbantime = timezone.now()  # 设置为当前时间
                    print(xueyuan.save())
            if commit:
                instance.save()
            return instance

class jiaowu_genjinlogForm(forms.ModelForm):
    class Meta:
        model = xueyuan_jiaowu_genjinlog
        fields = ['gengjin_time','gengjin_content']
        widgets = {
            'gengjin_time': forms.DateInput(attrs={'type': 'datetime-local','class': 'form-control'}),
            'gengjin_content': forms.Textarea(attrs={'cols':30 ,'rows':5,'class': 'form-control'}),
        }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['gengjin_time'].label = "添加日期"

class Xueyuan_zongbiao_form(forms.ModelForm):
    class Meta:
        model = Xueyuan_zongbiao
        fields = (
            'xueyuan_jinbantime',
            'baomingtime',
            'shenfenzheng',
            'wenhuachengdu',
            'jiguan',
            'xueyuan_zhengjian_img',
            'xueyuan_zhengjian_shouming',
            'beizhu',
            'xueyuan_zhengjian_opentime',
            'xueyuan_zhengjian_endtime',
        )
        widgets = {
            'xueyuan_jinbantime': forms.DateTimeInput(attrs={'class': 'form-control float-left', 'type': 'datetime-local'}),
            'baomingtime':  forms.DateTimeInput(attrs={'class': 'form-control float-left', 'type': 'datetime-local'}),
            'shenfenzheng': forms.TextInput(attrs={'class': 'form-control float-left'}),
            'wenhuachengdu': forms.TextInput(attrs={'class': 'form-control float-left'}),
            'jiguan': forms.TextInput(attrs={'class': 'form-control float-left'}),
            'xueyuan_zhengjian_img': forms.FileInput(attrs={'class': 'form-control float-left'}),
            'xueyuan_zhengjian_shouming': forms.Textarea(attrs={'class': 'form-control float-left', 'rows': '3', 'cols': '100px'}),
            'beizhu': forms.Textarea(attrs={'class': 'form-control float-left', 'rows': '3', 'cols': '100px'}),
            'xueyuan_zhengjian_opentime':forms.DateTimeInput(attrs={'class': 'form-control float-left', 'type': 'datetime-local'}),
            'xueyuan_zhengjian_endtime': forms.DateTimeInput(attrs={'class': 'form-control float-left', 'type': 'datetime-local'}),
        }

    def clean_tel(self):
        tel = self.cleaned_data.get('tel')
        # 如果是更新操作，并且当前实例的电话号码没有改变，则不触发验证
        if self.is_update and self.instance.pk and self.instance.tel == tel:
            return tel
        # 如果是新增操作或者电话号码已更改，则检查重复
        if KeHu.objects.filter(tel=tel).exclude(pk=self.instance.pk).exists():
            raise forms.ValidationError('该手机号码已存在，请重新输入。')
        return tel

class ZhengShi_XueYuanziliao_form(forms.ModelForm):
    class Meta:
        model = Xueyuan_Zilao
        fields = ('xueyuan', 'xm','xb')
        widgets = {
            'xueyuan': forms.Select(attrs={'class': 'form-control'}),
            'xm': forms.TextInput(attrs={'class': 'form-control'}),
            'xb': forms.TextInput(attrs={'class': 'form-control'}),
            'yxlzmcl':forms.Select(attrs={'class': 'form-control'}),
        }


class Xueyuan_Zilao_Update_Form(forms.ModelForm):
    class Meta:
        model = Xueyuan_Zilao
        # 使用列表推导式来定义fields，省略了重复的字段定义
        #fields =('xm',)
        fields = [f.name for f in Xueyuan_Zilao._meta.get_fields() if f.name not in ('id', 'xueyuan')]
        exclude = ('zongbiao',)


    def form_invalid(self, form):  # 处理表单无效的情况
        print("form_invalid---表单无效 -或者数据不存在")
        pass

class Xueyuan_Add_Form(forms.ModelForm):
    class Meta:
        model = KeHu
        fields = ('username', 'tel', 'wechat', 'qq',  'tg_qudao')